import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Checkbox,
  Modal,
  Badge,
  Divider,
  Radio,
  Menu,
  Icon,
  Dropdown,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {nameMaxLength,remarkMaxLength,contentLength,regLength} from '@/utils/rule'
import styles from '../search.less';
const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(id => obj[id])
    .join(',');
const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];
const formLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const CreateForm = Form.create()(props => {

  const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible ,
    form: {getFieldValue },
    text,
    matching,
    grouping,
    validating,
    matchData,
    groupData,
    validateData,
    changeValidateData,
  } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(text) {
        updateFn(fieldsValue,text)
      }else{
        addDataFn(fieldsValue);
      }
    });
  };

  // matchingContent +Reg  = matchingResult
  const getMatching = () => {
      const matchingContent = form.getFieldValue('testContent');
      const Reg = form.getFieldValue('reg');

      matching({matchingContent,Reg})
  }

// ReplaceReg+MatchingResult = groupList
  const getGrouping = () => {
      const ReplaceReg = form.getFieldValue('replaceReg');
      const MatchingResult = form.getFieldValue('MatchingResult');

      grouping({ReplaceReg,MatchingResult})
  }

// MatchingContent+GroupList+Reg+ReplaceReg=matchingResult
  const getValidating = () => {
      const whichList = groupData&&groupData.length&&form.getFieldValue('groupResult') || [];
      const MatchingContent = form.getFieldValue('testContent');
      const Reg = form.getFieldValue('reg');

      const GroupList = form.getFieldValue('replaceMode')==1?whichList.join(","):'';
      const ReplaceReg = form.getFieldValue('replaceReg');

      validating({MatchingContent,Reg,GroupList,ReplaceReg})
  }

  const changeResult = () => {
    changeValidateData()
  }
  const groupStyle = {
    display: 'inline-block',
    width: '100%',
    border: '1px solid #ccc',
    borderRadius: '3px',
    padding: '10px',
    minHeight: '80px',
    background: 'aliceblue',
  }

  const checkFun = (data) => {
    data[0].map( (v,i) => {
      let valueN = '';
      data.map( (item,index) => {
        if(index == resultL[0].length-1){
          valueN = (valueN + item[i]);
        }else{
          valueN = (valueN + item[i]) + ',';
        }
      })
      return (
        <Checkbox value={i+1}>第{i+1}组：{valueN }</Checkbox>
      )
    })
  }
  const resultL = JSON.parse(text && text.groupResult && text.groupResult || "[]");

  return (
    <Modal
      destroyOnClose
      width={640}
      title={text?'编辑脱敏规则':'新增脱敏规则'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem {...formLayout} label="规则名称">
        {form.getFieldDecorator('ruleName', {
          rules: [{required: true,message:'规刚名称不能为空'},{max:nameMaxLength()[0],message:nameMaxLength()[1]}],initialValue: text&&text.ruleName||''
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem {...formLayout} label="测试内容">
        {form.getFieldDecorator('testContent',{initialValue: text&&text.testContent||'',
          rules: [{ required: true, message: '请输入测试内容'},{max:contentLength()[0],message:contentLength()[1]}],
          })(<TextArea
          style={{minHeight: 32}}
          placeholder="多个测试内容用逗号隔开"
          rows={3}
        />)}
      </FormItem>

      <FormItem {...formLayout} label="匹配规则">
        <div style={{position:'absolute',left:'-60px',top:'-15px'}}><Button type="primary" size="small" onClick={getMatching}>匹配</Button></div>
        {form.getFieldDecorator('reg', {
          rules: [{required: true,message:'匹配规则不能为空'},{max:regLength()[0],message:regLength()[1]}],initialValue: text&&text.reg||''
        })(<TextArea
          style={{minHeight: 32}}
          placeholder="请输入"
          rows={3}
        />)}
      </FormItem>

      <FormItem {...formLayout} label="匹配结果">
        {form.getFieldDecorator('MatchingResult',{initialValue:text&&!(matchData&&matchData.length)?text.matchingResult:(matchData&&matchData.length&&matchData.join(',')||'')})(<TextArea
          style={{minHeight: 32}}
          placeholder=""
          rows={3}
          disabled={true}
        />)}
      </FormItem>

      <FormItem {...formLayout} label="替换方式">
        {form.getFieldDecorator('replaceMode', {
          rules: [{required: true,}],initialValue:text&&text.replaceMode||0
        })(
          <Radio.Group onChange={changeResult}>
            <Radio value={0}>
              默认
            </Radio>
            <Radio value={1}>
              分组替换
            </Radio>
          </Radio.Group>
        )}
      </FormItem>


      <FormItem {...formLayout} label={getFieldValue('replaceMode') == 0?'替换正则':'分组正则'}>
        <div style={{position:'absolute',left:'-60px',top:'-15px'}}>
          {getFieldValue('replaceMode') == 0?(
            <Button type="primary" size="small" onClick={getValidating}>替换</Button>
          ):(
            <Button type="primary" size="small" onClick={getGrouping}>分组</Button>
          )}
        </div>
        {form.getFieldDecorator('replaceReg', {initialValue: text&&text.replaceReg || '',
          rules: [{required: true,message:'正则不能为空'},{max:regLength()[0],message:regLength()[1]}],

        })(<TextArea
          style={{minHeight: 32}}
          placeholder="请输入"
          rows={3}
        />)}
      </FormItem>

      <FormItem {...formLayout} label="分组结果" style={{display: getFieldValue('replaceMode') == 1 ? 'block' : 'none',}}>
        <div style={{position:'absolute',left:'-60px',marginTop:'25px'}}><Button type="primary" size="small" onClick={getValidating}>替换</Button></div>
        {form.getFieldDecorator('groupResult',{initialValue: text&&text.groupList&&text.groupList.split(",") || []
        })(
          <CheckboxGroup style={groupStyle} >
          {
            text && resultL && !(groupData&&groupData.length) && resultL.length ? resultL[0].map( (v,i) => {
                let valueN = '';
                resultL.map( (item,index) => {
                  if(index == resultL[0].length-1){
                    valueN = (valueN + item[i]);
                  }else{
                    valueN = (valueN + item[i]) + ',';
                  }
                })
                return (
                  <Checkbox key={i+1} value={(i+1)+''}>第{i+1}组：{valueN }</Checkbox>
                )
            }) : groupData && groupData.length ? groupData[0].map( (v,i) => {
              let valueN = '';
              groupData.map( (item,index) => {
                if(index == groupData[0].length-1){
                  valueN = (valueN + item[i]);
                }else{
                  valueN = (valueN + item[i]) + ',';
                }
              })
              return (<Checkbox key={i+1} value={(i+1)+''}>第{i+1}组：{valueN }</Checkbox>)
            }) : null
          }
          </CheckboxGroup>
        )}
      </FormItem>

      <FormItem {...formLayout} label="替换结果" style={{display: getFieldValue('replaceMode') == 1 ? 'none' : 'block',}}>
        {form.getFieldDecorator('replaceResult',{initialValue:text&&!(validateData&&validateData.length)?text.replaceResult:(validateData&&validateData.length&&validateData.join(',')||'')})(<TextArea
          style={{minHeight: 32}}
          placeholder=""
          rows={3}
          disabled={true}
        />)}
      </FormItem>

      <FormItem {...formLayout} label="替换结果" style={{display: getFieldValue('replaceMode') == 1 ? 'block' : 'none',}}>
        {form.getFieldDecorator('replaceResult2',{initialValue:text&&!(validateData&&validateData.length)?text.replaceResult:(validateData&&validateData.length&&validateData.join(',')||'')})(<TextArea
          style={{minHeight: 32}}
          placeholder=""
          rows={3}
          disabled={true}
        />)}
      </FormItem>

      <FormItem {...formLayout} label="备注">
        {form.getFieldDecorator('remark', {initialValue: text&&text.remark,
          rules: [{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}],
          })(<TextArea
          style={{minHeight: 32}}
          placeholder="请输入"
          rows={2}
        />)}
      </FormItem>

      <FormItem {...formLayout} label="状态" style={{display: text == null ? 'none' : 'block'}}>
        {form.getFieldDecorator('state', {initialValue: text&&text.state
        })(<Radio.Group>
            <Radio value={0}>
              启用
            </Radio>
            <Radio value={1}>
              禁用
            </Radio>
          </Radio.Group>
        )}
      </FormItem>

    </Modal>
  );
});

@Form.create()
/* eslint react/no-multi-comp:0 */
@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.rule,
}))
@Form.create()
class rule extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    text: {},
    //详情
    detailVisible: false,
    detailsData: {},
  };


  columns = [
    {
      title: '规则名称',
      dataIndex: 'ruleName',
    },
    {
      title: '匹配规则',
      dataIndex: 'reg',
      width:'25%',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '替换正则',
      dataIndex: 'replaceReg',
      width:'25%',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'state',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.detailHandelVisible(true,text)}>详情</a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item onClick={() => this.handleModalVisible(true, record)}>编辑</Menu.Item>
                <Menu.Item onClick={() => this.deleteData(text.id)}>删除</Menu.Item>
              </Menu>
            }
          >
            <a>更多 <Icon type="down"/></a>
          </Dropdown>
{/*
          <a onClick={() => this.handleModalVisible(true, record)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleThisRowDelete(record.id)}>删除</a>*/}
        </Fragment>
      ),
    },
  ];


  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/queryList',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      pageNum: pagination.current-1,
      pageSize: pagination.pageSize,
      ...formValues,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'rule/queryList',
      payload: params,
    });
  };

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };

   batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  handleThisRowDelete = (ids) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/remove',
      payload: {ids},
      callback: (res) => {
        if(res.result == "ok") {
         Modal.success({title: res.msg});
          dispatch({
            type: 'rule/queryList',});
          this.setState({selectedRows: []})
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'rule/queryList',
        payload: values,
      });
    });
  };

  handleModalVisible = (flag,text) => {
    this.setState({
      modalVisible: !!flag,
      text: text,
      matchData: [],
      groupData: [],
      validateData: [],
    });
  };

  detailHandelVisible = (flag,text) => {
    this.setState({
      detailVisible: !!flag,
      detailsData: text,
    });
  };

  //新增
  addDataFn = fields => {
    const { dispatch } = this.props;
    const { groupData } = this.state;
    dispatch({
      type: 'rule/add',
      payload: {
        ruleName: fields.ruleName,
        testContent: fields.testContent,
        reg: fields.reg,
        matchingResult: fields.MatchingResult,
        replaceMode: fields.replaceMode,
        replaceReg: fields.replaceReg,
        replaceResult: fields.replaceMode==0?fields.replaceResult:fields.replaceResult2,
        groupRegular: fields.replaceReg,
        groupResult: JSON.stringify(groupData),
        groupList: fields.groupResult&&fields.groupResult.join(",")||'5555',
        remark: fields.remark,
      },
      callback: (res) => {
        if(res.result == "ok") {
         Modal.success({title: res.msg});
          dispatch({
            type: 'rule/queryList',});
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  //编辑
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const { groupData } = this.state;
    const groupResult = groupData&&groupData.length?JSON.stringify(groupData):text.groupResult;
    dispatch({
      type: 'rule/update',
      payload: {
        ruleName: fields.ruleName,
        testContent: fields.testContent,
        reg: fields.reg,
        matchingResult: fields.MatchingResult,
        replaceMode: fields.replaceMode,
        replaceReg: fields.replaceReg,
        replaceResult: fields.replaceMode==0?fields.replaceResult:fields.replaceResult2,
        groupRegular: fields.replaceReg,
        state: fields.state,
        groupResult,
        groupList: fields.groupResult&&fields.groupResult.join(",")||'',
        remark: fields.remark,
        id: text.id,
      },

      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'rule/queryList',});
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });

    this.handleModalVisible();
  };

  // 匹配内容+匹配规则  点击匹配  得出匹配结果
  matching(params) {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/matching',
      payload:params,
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            matchData: res.data.matchList,
          })
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

   // 替换正则+匹配结果 = 分组结果
  grouping(params) {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/grouping',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            groupData: res.data,
          })
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

   //匹配内容+分组列表，逗号隔开+正则+替换正则 = 结果
  validating(params) {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/validating',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            validateData: res.data.list,
          })
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  changeValidateData() {
    this.setState({
      validateData: [],
    })
  }

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="规则名称">
              {getFieldDecorator('ruleName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      rule: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, stepFormValues,matchData,groupData,validateData,text,detailVisible, detailsData } = this.state;

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      matching: this.matching.bind(this),
      grouping: this.grouping.bind(this),
      validating: this.validating.bind(this),
      changeValidateData: this.changeValidateData.bind(this),
      addDataFn: this.addDataFn,
      updateFn: this.updateFn
    };
    const updateMethods = {
      handleUpdate: this.handleUpdate,
      matching: this.matching.bind(this),
      grouping: this.grouping.bind(this),
      validating: this.validating.bind(this),
      changeValidateData: this.changeValidateData.bind(this),
    };
    const detailsMethods = {
      detailHandelVisible: this.detailHandelVisible,
    };
    return (
      <PageHeaderWrapper title="敏感规则">
      <Card bordered={false}>
        <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
          matchData={matchData}
          groupData={groupData}
          validateData={validateData}
          text={text}
        />
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            rowKey={record => record.id}
          />
          {detailsData&&detailsData.id?(
          <Details {...detailsMethods} detailVisible={detailVisible} detailsData={detailsData} />
        ):null}
        </div>
      </Card>
      </PageHeaderWrapper>
    );
  }
}

class Details extends PureComponent {

  render() {
    const { detailVisible, detailHandelVisible, detailsData } = this.props;
  return (
    <Modal
      destroyOnClose
      width={800}
      title="查看脱敏规则"
      visible={detailVisible}
      onOk={() => detailHandelVisible()}
      onCancel={() => detailHandelVisible()}
      footer={[
        <Button key="back" type="primary" onClick={() => detailHandelVisible()}>返回</Button>
      ]}
      className={styles.viewMore}
    >
      <Row>
        <Col md={12}>
          <FormItem labelCol={{span: 8}} wrapperCol={{span: 16}} label="规则名称">
           {detailsData.ruleName}
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem labelCol={{span: 8}} wrapperCol={{span: 16}} label="状态">
            {detailsData.state==0?'启用':'禁用'}
          </FormItem>
        </Col>

        <Col md={24}>
          <FormItem {...formLayout} label="测试内容">
            {detailsData.testContent}
          </FormItem>
        </Col>

        <Col md={24}>
          <FormItem {...formLayout} label="匹配规则">
            {detailsData.reg}
          </FormItem>
        </Col>

        <Col md={24}>
          <FormItem {...formLayout} label="匹配结果">
            {detailsData.matchingResult}
          </FormItem>
        </Col>


        <Col md={24}>
          <FormItem {...formLayout} label="替换方式">
            {detailsData.replaceMode==0?'默认':'分组替换'}
          </FormItem>
        </Col>


        <div style={{display: detailsData.replaceMode==0? 'block' : 'none'}}>
          <Col md={24}>
            <FormItem {...formLayout} label="替换正则">
              {detailsData.replaceReg}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem {...formLayout} label="替换结果">
              {detailsData.replaceResult}
            </FormItem>
          </Col>
        </div>


        <div style={{display: detailsData.replaceMode==1? 'block' : 'none',}}>
          <Col md={24}>
            <FormItem {...formLayout} label="分组正则">
              {detailsData.groupRegular}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem {...formLayout} label="分组结果">
              {detailsData.groupResult}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem {...formLayout} label="替换结果">
              {detailsData.replaceResult}
            </FormItem>
          </Col>
        </div>

        <Col md={24}>
          <FormItem {...formLayout} label="备注">
            {detailsData.remark}
          </FormItem>
        </Col>
        <Col md={24}>
          <FormItem {...formLayout} label="创建时间">
            {moment(detailsData.createTime).format('YYYY-MM-DD HH:mm')}
          </FormItem>
        </Col>
      </Row>
    </Modal>
  );
  }
}

export default rule;
